﻿
using LinqKit;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.StaticFiles;
using Newtonsoft.Json.Linq;
using SqlSugar;
using WCS.Entities;
using WCS.Entities.Api;

namespace WCS.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class LogController : ControllerBase
    {

        /// <summary>
        /// 分页查找
        /// </summary>
        /// <param name="page">当前页码</param>
        /// <param name="limit">每页大小</param>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult> GetLogsByPage(int page, int limit, [FromQuery] string query)
        {
            try
            {
                FileInfo[]? files = null;
                await Task.Run(() =>
                {
                    var rootPath = AppDomain.CurrentDomain.BaseDirectory;
                    var root = new DirectoryInfo(System.IO.Path.Combine(rootPath, "logs"));
                    files = root.GetFiles();
                });

                var fileInfos = files.Select(x => new LogInfo { FileName = x.Name, Url = x.FullName, CreateTime = x.CreationTime, UpdateTime = x.LastAccessTime, Size = x.Length / 1024.0f }).ToArray();
                if (query != null)
                {
                    JObject jobject = JObject.Parse(query);
                    var predicate = PredicateBuilder.New<LogInfo>(true);
                    foreach (var key in jobject.Properties())
                    {
                        if (string.IsNullOrEmpty(key.Value.ToString()))
                            continue;
                        if (key.Name.ToString().ToLower() == "createtime")
                        {
                            predicate.And(x => x.CreateTime > Convert.ToDateTime(key.Value[0]));
                            predicate.And(x => x.CreateTime < Convert.ToDateTime(key.Value[1]));

                        }

                        if (key.Name.ToString().ToLower() == "updatetime")
                        {
                            predicate.And(x => x.UpdateTime > Convert.ToDateTime(key.Value[0]));
                            predicate.And(x => x.UpdateTime < Convert.ToDateTime(key.Value[1]));

                        }

                    }

                    var result = fileInfos.Where(predicate.Compile()).Skip((page - 1) * limit).Take(limit).ToArray();
                    return ApiResultHelp.Success(new { list = result, total = result.Length });

                }
                else
                {
                    var result = fileInfos.Skip((page - 1) * limit).Take(limit).ToArray();
                    return ApiResultHelp.Success(new { list = result, total = fileInfos.Length });

                }
            }
            catch (Exception ex)
            {
                return ApiResultHelp.Error($"查询出错:{ex.Message}");
            }
        }

        /// <summary>
        /// 下载日志
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        [HttpGet()]
        public async Task<FileResult> DownFile([FromQuery] string path)
        {
            var stream = System.IO.File.OpenRead(path);
            string contentType = await Task.Run(() =>
            {
                string suffix = System.IO.Path.GetExtension(path);
                var provider = new FileExtensionContentTypeProvider();
                provider.Mappings[".log"] = "text/plain";
                var contentType = provider.Mappings[suffix];
                return contentType;
            });
            return File(stream, contentType, System.IO.Path.GetFileName(path));



        }
    }
}
